package com.lxb.eduservice.controller;


import com.lxb.commonutils.R;
import com.lxb.eduservice.client.VodClient;
import com.lxb.eduservice.entity.EduVideo;
import com.lxb.eduservice.service.EduVideoService;
import com.lxb.servicebase.exceptionhandler.GuliException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 课时管理
 *
 * @author lixuebin
 * @since 2022-11-06
 */
@Api(description = "课时管理")
@RestController
@RequestMapping("/eduservice/video")
//@CrossOrigin
public class EduVideoController {

    @Autowired
    private EduVideoService eduVideoService;
    @Autowired
    private VodClient vodClient;

    @ApiOperation(value = "添加小节")
    @PostMapping("/addVideo")
    public R addVideo(
            @ApiParam(name = "eduVideo", value = "课程视频", required = true)
            @RequestBody EduVideo eduVideo) {
        boolean save = eduVideoService.save(eduVideo);
        return save ? R.ok() : R.error().message("添加小节成功");
    }

    /**
     * 逻辑设计：先删除小节表的 阿里云端视频，后再删除小节信息
     * @param id
     * @return
     */
    @ApiOperation(value = "删除小节")
    @DeleteMapping("/deleteVideo/{id}")
    public R deleteVideo(@PathVariable String id) {

        //根据小节id，获取视频id
        EduVideo eduVideo = eduVideoService.getById(id);

        //判断是否有视频id
        if (StringUtils.isNotEmpty(eduVideo.getVideoSourceId())) {
            //远程调用来实现删除视频
            vodClient.deleteVideoByID(eduVideo.getVideoSourceId());
        }

        //删除小节
        boolean b = eduVideoService.removeById(id);
        return b ? R.ok() : R.error().message("删除小节信息失败");
    }

    @ApiOperation(value = "根据id查询小节信息")
    @GetMapping("/videoInfo/{id}")
    public R getVideoInfoById(@PathVariable String id){
        EduVideo eduVideo = eduVideoService.getById(id);
        if(eduVideo == null){
            throw new GuliException(20001,"数据不存在");
        }
        return R.ok().data("eduVideInfo",eduVideo);
    }

    @ApiOperation(value = "更新小节信息")
    @PostMapping("/updateVideoInfo")
    public R updateVideoInfo(
            @ApiParam(value = "小节信息", required = true)
            @RequestBody EduVideo eduVideo) {

        boolean update = eduVideoService.updateById(eduVideo);

        if (!update) {
            return R.error().message("更新失败");
        }
        return R.ok();
    }
}

